<template>
  <uni-nav-bar title="新增加注站" left-icon="left" @clickLeft="navBack" statusBar></uni-nav-bar>
  <view class="package" style="padding:0px 20rpx;">
    <view class="space-between">
      <view>加注站名称</view>
      <input class="uni-input" placeholder="请输入加注站名称" v-model="name" />
    </view>
    <view class="space-between">
      <view>补液单价</view>
      <input class="uni-input" placeholder="请输入补液单价" v-model="price" />
    </view>
    <view class="space-between" @click="chooseLocation()" style="align-items: flex-start;">
      <view>位置</view>
      <view style="width: 75%;text-align: right;">{{locName}}</view>
    </view>
  </view>
  <view class="add" @click="submit()">确定</view>
  <!-- 选择地址列表 -->
  <view v-if="curPage === 'map'"><web-view :src="mapURI"></web-view></view>
  <!-- 当前位置经纬度 -->
  <Lotlats @position="position"></Lotlats>
</template>

<script setup lang="ts">
  import { navBack } from '@/utils/navigator';
  import { ref, Ref } from 'vue';
  import * as AMapLoader from '@amap/amap-jsapi-loader';
  import { toPublish } from '@mqtt';
  import Lotlats from '@c/team/Lotlat.vue';
  import { errorToast, showLoading, successToast } from '@/utils/prompt';
  const name = ref('')
  const price = ref('')
  // data
  const curPage : Ref<'form' | 'map'> = ref('form');
  const longitude = ref()
  const latitude = ref()
  const mapURI = ref('');
  const locName = ref('')
  /**
   * 获取当前城市信息
   * @param  lat 当前位置的纬度
   * @param  lot 当前位置的经度
   */
  function position(lat : number, lot : number) {
    longitude.value = lot;
    latitude.value = lat;
    getPositionByLonLats(lot, lat)
  }
  function getPositionByLonLats(lng : number, lat : number) {
    AMapLoader.load({
      key: '28c93d7518383bfa130b6c7cd239c331', // 申请好的Web端开发者Key，首次调用 load 时必填  
      version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: ['AMap.Geocoder', 'AMap.Geolocation'] //插件列表
    })
      .then(AMap => {
        const lnglat = [lng, lat]
        const geocoder = new AMap.Geocoder()
        geocoder.getAddress(lnglat, function (status : any, result : any) {
          if (status === 'complete' && result.regeocode) {
            locName.value = result.regeocode.formattedAddress
          } else {
            console.log('根据经纬度查询地址失败')
          }
        })
      })
  }
  /**
   * 跳转到地址列表 选择位置信息
   */
  function chooseLocation() {
    mapURI.value = `https://apis.map.qq.com/tools/locpicker?coord=${latitude.value},${longitude.value}&search=1&type=1&key=URFBZ-F4TKI-SLPGX-57GMO-ZHYM6-BCFSL&referer=安蓝环保`;
    curPage.value = 'map';
    function msgListener(event : any) {
      // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
      var loc = event.data;
      if (loc && loc.module == 'locationPicker') {
        console.log(JSON.stringify(loc) + '*****')
        curPage.value = 'form';
        longitude.value = loc.latlng.lng;
        latitude.value = loc.latlng.lat;
        locName.value = loc.poiaddress
        //防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
        window.removeEventListener('message', msgListener);
      }
    }
    window.addEventListener('message', msgListener, false);
  }
  function submit() {
    if (!name.value) {
      errorToast('请输入加注站名称')
      return
    }
    if (!price.value) {
      errorToast('请输入补液单价')
      return
    }
    if (!locName.value) {
      errorToast('请选择加注站位置')
      return
    }
    showLoading()
    const payload = {
      name: name.value,
      price: price.value,
      longitude: longitude.value,
      latitude: latitude.value,
      address: locName.value
    };
    toPublish(
      'control/addDelivery',
      payload,
      (obj : any) => {
        uni.hideLoading();
        const { code, msg } = obj;
        if (code === 1) {
          successToast(msg)
          navBack()
        } else {
          errorToast(msg)
        }
      }
    );
  }
</script>

<style scoped lang="less">
  .add {
    width: 480rpx;
    height: 100rpx;
    background: linear-gradient(-10deg, #2C96F9, #1B91FF);
    border-radius: 5px;
    text-align: center;
    line-height: 100rpx;
    color: #fff;
   margin: 60rpx auto 20rpx;
    font-size: 32rpx;
  }

  .space-between:nth-last-child(1) {
    border-bottom: 0px;
  }

  .space-between {
    padding: 30rpx 0px;
    border-bottom: 1px solid #eee;

    input {
      text-align: right;
    }
  }
</style>